# Load functions and data (once)
#setwd("C:/Users/Patrik/Dropbox/Lindenfors & Jansson/R/Replication")
source("functions.R")
require(foreign)  
library(xlsx) 
data.all <- read.csv("DataMethods1.csv",sep = ";",dec = ".")
data.all[,names(data.all)[grep("5C",names(data.all))]] <- round(data.all[,names(data.all)[grep("5C",names(data.all))]] * 4)
npols <- apply(data.all[,c(names(data.all)[grep("5C",names(data.all))])],2,max,na.rm=T) + 1
data <- split(data.all,as.factor(data.all$country_id))
output.ttm <- function (s,t) write.table(t,paste("",s,".csv",sep=""),row.names=F,col.names=T,sep=";",dec=",")

#Tables
data.states <- data.all[unique.values(data.all,c("v2x_EDcomp_thick5C","v2x_freexp5C")),]
tlX <- freq.tables(data.states,c("v2x_EDcomp_thick5C","v2x_freexp5C"))
write.tables(tlX,"EDcompFreexpTables.csv")

data.states <- data.all[unique.values(data.all,c("v2x_EDcomp_thick5C","v2xme_altinf5C")),]
tlX <- freq.tables(data.states,c("v2x_EDcomp_thick5C","v2xme_altinf5C"))
write.tables(tlX,"EDcompAltInfTables.csv")

data.states <- data.all[unique.values(data.all,c("v2x_freexp5C","v2xme_altinf5C")),]
tlX <- freq.tables(data.states,c("v2x_freexp5C","v2xme_altinf5C"))
write.tables(tlX,"FreexpAltinfTable.csv")

ttm <- trans.trans(data,"v2x_EDcomp_thick5C","v2x_freexp5C")
output.ttm("EDcompFreexpResults",ttm)

ttm <- trans.trans(data,"v2x_EDcomp_thick5C","v2xme_altinf5C")
output.ttm("EDcompAltinfResults",ttm)

ttm <- trans.trans(data,"v2x_freexp5C","v2xme_altinf5C")
output.ttm("FreexpAltinfResults",ttm)



myvars <- c("v2x_EDcomp_thick5C", "v2x_freexp5C", "v2xme_altinf5C",
            "v2x_suffr5C","v2clprptym_ord","v2clprptyw_ord","v2elrgstry_ord","v2elintim_ord","v2cldmovem_ord","v2cldmovew_ord",
            "v2psparban_ord","v2psbars_ord","v2psoppaut_ord","v2meslfcen_ord","v2csreprss_ord","v2cseeorgs_ord","v2mebias_ord",
            "v2lgoppart_ord","v2elembaut_ord","v2jucomp_ord","v2clacjstm_ord", "v2clacjstw_ord","v2meharjrn_ord",
            "v2juhcind_ord","v2lgotovst_ord")
ql <- quantile.by.value.all(data.all,myvars,0.05)
write.xlsx.list(ql,"Contingencies.xlsx",col.names=T, row.names=T, showNA=TRUE)
ql <- quantile.by.value.all(data.all,myvars,0)
write.xlsx.list(ql,"Contingencies0.xlsx",col.names=T, row.names=T, showNA=TRUE)
data.states <- data.all[unique.values(data.all,myvars[1:3]),]
#tlX <- freq.tables(data.states,myvars[1:3])
tlOD <- freq.off.diags(tlX)
write.xlsx(tlOD,"Frequencies.xlsx",col.names=T, row.names=T, append=FALSE, showNA=TRUE)
#write.tables(tlX,"Tables.csv")
#write.xlsx(tlX,"Tables.xlsx")



#Figures
library(igraph)
library(dplyr)
library(ggplot2)

filenames <- c("EDcompFreexp","EDcompAltinf","FreexpAltinf")
xlabs <- c("Freedom of expression","Alternative source information","Alternative source information")
ylabs <- c("Electoral Component Index","Electoral Component Index","Freedom of expression")

for (k in 1:3) {
  
#import the matrix
poly.m<-read.csv(paste(filenames[k],"Results.csv",sep=""), sep = ";" ,header = T)

#create a "adjacency matrix" and transform the original matrix into the correct format
poly.node<-matrix(NA, nrow=25,ncol=25)
for(i in 1:5){
  for(j in 1:5){
    poly.node[seq(i,20+i,5),seq(j,20+j,5)]<-t(matrix(poly.m[,(i-1)*5+j],nrow=5,ncol=5))
  }
}

#get rid of the "stasis"
diag(poly.node) <- 0
for (i in seq(1,25,6)){
  for (j in seq(1,25,6)){
    poly.m[i,j]<-0
  }
}

#add empty row and colnames
colnames(poly.node)<-c(" "," "," "," "," ",
                       " "," "," "," "," ",
                       " "," "," "," "," ",
                       " "," "," "," "," ",
                       " "," "," "," "," ")


#create a list of the number of "lands on"
size.list<-rep(NA, 25)
for (i in 1:25){
  size.list[i]<-sum(poly.m[seq(ceiling(i/5),ceiling(i/5)+20,5),(i-1)%%5+1])+
    sum(poly.m[seq(ceiling(i/5),ceiling(i/5)+20,5),(i-1)%%5+6])+
    sum(poly.m[seq(ceiling(i/5),ceiling(i/5)+20,5),(i-1)%%5+11])+
    sum(poly.m[seq(ceiling(i/5),ceiling(i/5)+20,5),(i-1)%%5+16])+
    sum(poly.m[seq(ceiling(i/5),ceiling(i/5)+20,5),(i-1)%%5+21])
}

#graphing
g=graph.adjacency(poly.node,mode="directed",weighted=T)
V(g)$size=size.list/5
V(g)$color <- "skyblue"
tiff(filename = paste(filenames[k],".tif",sep=""),width = 2500, height = 2500, units = "px", pointsize = 80, compression = "none")
plot(g, layout=layout.grid(g,width=5),edge.width=E(g)$weight/3,edge.curved=TRUE,
     edge.arrow.size=E(g)$weight/100,edge.arrow.width=E(g)$weight/100,
     xlab=xlabs[k], ylab=ylabs[k])
x <- c(0:4)
axis(1, at=(x/2)-1,labels=x)
axis(2, at=(x/2)-1,labels=x, las = 2)
dev.off()

}
